package com.axxc.cloud.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.alibaba.fastjson.JSONObject;

class BaseController {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Value("${axxc.validate}")
	private Boolean enableValidate;

	protected String toJson(Object obj) {
		if (obj == null) {
			return null;
		} else {
			return JSONObject.toJSONString(obj);
		}
	}

	private static final ThreadLocal<HttpServletRequest> requestContainer = new ThreadLocal<HttpServletRequest>();

	private static final ThreadLocal<HttpServletResponse> responseContainer = new ThreadLocal<HttpServletResponse>();

	private static final ThreadLocal<ModelMap> modelContainer = new ThreadLocal<ModelMap>();

	/**
	 * 初始化response
	 * 
	 * @param response
	 */
	@ModelAttribute
	private final void initResponse(HttpServletResponse response) {
		responseContainer.set(response);
	}

	/**
	 * 获取当前线程的response对象
	 * 
	 * @return
	 */
	protected final HttpServletResponse getResponse() {
		return responseContainer.get();
	}

	/**
	 * 初始化request
	 * 
	 * @param request
	 */
	@ModelAttribute
	private final void initRequest(HttpServletRequest request) {
		if (enableValidate == null || enableValidate == true) {
			String requestTime = request.getParameter("t");
			String signature = request.getParameter("signature");
			if (StringUtils.isBlank(signature) || StringUtils.isBlank(requestTime)) {
				throw new IllegalArgumentException("缺少必传参数t or signature ");
			}
			Long timeA = Long.valueOf(requestTime);
			long timeB = System.currentTimeMillis() - timeA;

			// 10分钟之内
			if (timeB > 0 && timeB <= 600000) {
				String encode = Base64.encodeBase64String(timeA.toString().getBytes());
				System.out.println(encode);
				if (StringUtils.equals(signature, encode)) {
					requestContainer.set(request);
				} else {
					throw new IllegalArgumentException("无权访问");
				}
			} else {
				throw new IllegalArgumentException("超时访问");
			}
		} else {
			requestContainer.set(request);
		}

	}

	/**
	 * 获取当前线程的request对象
	 * 
	 * @return
	 */
	protected final HttpServletRequest getRequest() {
		return requestContainer.get();
	}

	/**
	 * 设置model
	 * 
	 * @param model
	 */
	@ModelAttribute
	private final void initModelMap(ModelMap model) {
		modelContainer.set(model);
	}

	/**
	 * 获取当前线程的modelMap对象
	 * 
	 * @return
	 */
	protected final ModelMap getModelMap() {
		return modelContainer.get();
	}
}
